<?php

namespace System\Core;

use \System\Types;

/**
 * Description of Benchmark
 *
 * @author elton.schivei
 */
final class Benchmark extends Types\Object
{

    private static $_instance;
    private static $_marker;

    function __construct()
    {
        parent::__construct();

        self::$_marker = array();
    }

    /**
     * @return Benchmark
     */
    public static function &GetInstance()
    {
        if (!self::$_instance)
            self::$_instance = new self();

        return self::$_instance;
    }

    // --------------------------------------------------------------------

    /**
     * Set a benchmark marker
     *
     * Multiple calls to this function can be made so that several
     * execution points can be timed
     *
     * @access	public
     * @param	string	$name	name of the marker
     * @return	void
     */
    public function Mark($name)
    {
        self::$_marker[$name] = microtime();
    }

    // --------------------------------------------------------------------

    /**
     * Calculates the time difference between two marked points.
     *
     * If the first parameter is empty this function instead returns the
     * {elapsed_time} pseudo-variable. This permits the full system
     * execution time to be shown in a template. The output class will
     * swap the real value for this variable.
     *
     * @access	public
     * @param	string	a particular marked point
     * @param	string	a particular marked point
     * @param	integer	the number of decimal places
     * @return	mixed
     */
    public function ElapsedTime($point1 = '', $point2 = '', $decimals = 4)
    {
        if ($point1 == '')
        {
            return '{elapsed_time}';
        }

        if (!isset(self::$_marker[$point1]))
        {
            return '';
        }

        if (!isset(self::$_marker[$point2]))
        {
            self::$_marker[$point2] = microtime();
        }

        list($sm, $ss) = explode(' ', self::$_marker[$point1]);
        list($em, $es) = explode(' ', self::$_marker[$point2]);

        return number_format(($em + $es) - ($sm + $ss), $decimals);
    }

    // --------------------------------------------------------------------

    /**
     * Memory Usage
     *
     * This function returns the {memory_usage} pseudo-variable.
     * This permits it to be put it anywhere in a template
     * without the memory being calculated until the end.
     * The output class will swap the real value for this variable.
     *
     * @access	public
     * @return	string
     */
    public function MemoryUsage()
    {
        return '{memory_usage}';
    }

}